<template>
    <div class="resourceDialog">
        <el-dialog
            class="resourceForm"
            :title="common.titleTips"
            :visible.sync="common.addResourceTab"
            :before-close="handleClose"
            :close-on-click-modal='false'>
            <el-form :model="resourceCon" :rules="newResRules" ref="resourceCon" label-width="100px" class="demo-ruleForm">
                <el-form-item v-if="common.type=='HDFS'" prop="url" label="目录名">
                    <el-input maxlength="12" v-model="resourceCon.url" :disabled="common.isDisabled" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item class="capUnit" v-if="common.type=='HDFS'" label="容量配额" prop="capacity">
                    <el-tooltip class="item" effect='dark' :content='remainTips' placement="top">
                        <el-input v-model.number="resourceCon.capacity" placeholder="请输入配额"></el-input>
                    </el-tooltip>
                    <el-select v-model="unit" placeholder="请选择" @change='getRemainTest'>
                        <el-option
                            v-for="item in resUnit"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="common.type=='HDFS'" label="文件配额" prop="fileNum">
                    <!-- <el-input @blur.prevent="getFileRemain" v-model.number="resourceCon.fileNum" placeholder="请输入文件数"></el-input> 个 -->
                    <el-tooltip class="item" effect='dark' :content='remainFileTips' placement="top">
                        <el-input v-model.number="resourceCon.fileNum" placeholder="请输入文件数"></el-input> 个
                    </el-tooltip>
                </el-form-item>
                
                <el-form-item v-if="common.type=='HBASE'" :label="resourceCon.clickStep==2?'表名':resourceCon.clickStep==3?'列族':''" prop="spaceName" >
                    <el-input maxlength="12" v-model="resourceCon.spaceName" :disabled="common.isDisabled" placeholder="请输入"></el-input>
                </el-form-item>

                <el-form-item v-if="common.type=='HIVE'" label="库名">
                    <el-input maxlength="12" v-model="resourceCon.name" :disabled="common.isDisabled"></el-input>
                </el-form-item>

            </el-form>
            <span slot='footer' class="dialog-footer">
                <el-button @click="cancelBtn('resourceCon')">取消</el-button>
                <el-button :loading="btnDisabled" type="primary" @click="submitResourceCon('resourceCon')">确认</el-button>
            </span>
        </el-dialog>
        <el-dialog
            class="resourceForm"
            :title="common.operatorTips"
            :visible.sync="common.resOperate"
            :close-on-click-modal='false'>
            <el-form label-width="100px" class="demo-ruleForm">
                <!-- opeBtn为1和2时是分配和分享 -->
                <span v-if="common.opeBtn == '1'||common.opeBtn == '2'">  
                    <el-form-item :label="common.label" prop="name">
                        <el-input v-model="resourceCon.url" placeholder="请输入" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item v-if="common.isShare=='0'" label="用户" prop="name">
                        <el-select
                            v-model="resourceCon.userList"
                            multiple
                            filterable
                            remote
                            reserve-keyword
                            placeholder="请输入用户名"
                            :remote-method="getUser"
                            :loading="loading">
                            <el-option
                                v-for="item in allUserList"
                                :key="item.userId"
                                :label="item.username"
                                :value="item.username">
                            </el-option>
                        </el-select>
                        支持多选
                    </el-form-item>
                    <el-form-item v-if="common.isShare=='1'" label="租户" prop="name">
                        <el-select
                            v-model="resourceCon.tenantList"
                            multiple
                            filterable
                            remote
                            reserve-keyword
                            placeholder="请输入租户名"
                            :remote-method="getTenant"
                            :loading="loading">
                            <el-option
                                v-for="item in tenantList"
                                :key="item.userId"
                                :label="item.username"
                                :value="item.username">
                            </el-option>
                        </el-select> 
                        支持多选
                    </el-form-item>
                </span>
                <span v-if="common.opeBtn == '4'">
                    <span v-if="common.type=='HDFS'">
                        <el-form-item label="资源名称">
                            {{common.editData.name}}
                        </el-form-item>
                        <el-form-item label="容量配额">
                            <span>{{common.editData.capacity}} {{common.editData.unit==1?'MB':common.editData.unit==2?"GB":common.editData.unit==3?'TB':''}}</span>
                        </el-form-item>
                        <el-form-item label="文件配额">
                            {{common.editData.fileNum}}
                        </el-form-item>
                        <el-form-item v-if="common.resTypeName == 'tenant'" label="共享的租户">
                            <span v-for="(item,index) in common.editData.tenantList" :key="index">
                                {{item}}
                                <span v-if="index!=common.editData.tenantList.length-1">,</span>
                            </span>
                        </el-form-item>
                        <el-form-item label="分配的用户">
                            <span v-for="(item,index) in common.editData.userList" :key="index">
                                {{item}}
                                <span v-if="index!=common.editData.userList.length-1">,</span>
                            </span>
                        </el-form-item>
                    </span>
                    <!-- <span v-if="common.type=='HDFS'">
                        <el-form-item label="资源名称">
                            {{common.editData.name}}
                        </el-form-item>
                        <el-form-item label="分配的用户">
                            <span v-for="(item,index) in common.editData.userList" :key="index">
                                {{item}}
                                <span v-if="index!=common.editData.userList.length-1">,</span>
                            </span>
                        </el-form-item>
                    </span> -->
                </span>
                <span v-if="common.opeBtn == '3'&&common.type!='YARN'">
                    <el-form-item label="是否保留数据" prop="name">
                        <el-switch v-model="idDelete" active-text="是" inactive-text="否"></el-switch>
                    </el-form-item>
                </span>
            </el-form>
            <span slot='footer' class="dialog-footer" v-if="common.opeBtn != '4'">
                <el-button @click="cancelBtn">取消</el-button>
                <el-button :loading="btnDisabled" type="primary" @click="submitTenant">确认</el-button>
            </span>
        </el-dialog>
        <el-dialog
            class="YARNForm resourceForm"
            :title='common.YARNtitle'
            :visible.sync="common.editYARN"
            :close-on-click-modal='false'>
            <el-table :data="resourcePublic" :rules="newResRules" stripe style="width: 100%" height="400">
                <el-table-column prop='queueName' :label="YARNtableHead[clickStep-1].first">
                    <template slot-scope="scope">
                        <el-input maxlength="12" v-if="scope.$index==0 && common.opeType==0" v-model='scope.row.queueName' placeholder="请输入队列名"></el-input>
                        <span v-else>{{scope.row.queueName}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="队列占比(%)" width="450">
                    <template slot-scope="scope">
                        <el-button class="countBtn" @click='changCount(0,scope.row.ratio,scope.$index)'>
                            <i class="el-icon-arrow-left"></i>
                        </el-button>
                        <el-slider @change='slideChange' class="slider" v-model="scope.row.ratio"></el-slider>
                        <span class="sliderSpan">{{scope.row.ratio}}</span>
                        <el-button class="countBtn" @click='changCount(1,scope.row.ratio,scope.$index)'>
                            <i class="el-icon-arrow-right"></i>
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <span slot='footer' class="dialog-footer">
                <span class="total">队列占比总计：{{total}} %</span>
                <el-button @click="cancelBtn">取消</el-button>
                <el-button :loading="btnDisabled" type="primary" @click="yarnEdit">确认</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { resUnit } from '@/const'
import { managerApi } from '@/request'
import { Message } from 'element-ui'
import resource from '@/mixins/resource'
    export default {
        props:['diaData'],
        mixins:[resource],
        data() {
            var validateUrl = (rule, value, callback) => {
                var reg = /(?!^(\d+)$)(?!^(_+)$)^[A-Za-z0-9_]{4,32}$/;
                if(!value){
                    return callback(new Error('请输入内容'));
                }
                if(value === ''){
                    callback(new Error('输入不能为空'));
                } else {
                    if(!this.common.isDisabled){//编辑的时候不校验
                        if(!reg.test(value)){
                            callback(new Error("只能输入长度不小于4位的数字、字母和'_'，并且不全为数字或'_'"));
                        }
                    }
                    callback();
                }
            }
            return {
                total: 0,
                common:{
                    label:'',
                    type: '',
                    addResourceTab: false,
                    titleTips: '',
                    isDisabled: false,
                    opeBtn:'1',
                    operatorTips: '',
                    resOperate: false,
                    resType: '1',
                    isShare:'0',
                    editYARN:false
                },
                idDelete: '1',
                resourceCon:{
                    name: '',
                    url: '',
                    capacity: '',
                    tenantList: [],
                    userList: [],
                    fileNum: '',
                    spaceName: '',
                    databaseName: ''
                },
                tenantList: [],
                newResRules: {
                    url: [
                        { required: true, validator: validateUrl, trigger: 'blur' },
                        { min: 4, max: 12, message: '长度在 4 到 12 个字符', trigger: 'blur' }
                    ],
                    capacity: [
                        { type:'number', min: 0, required: true, message: '请输入配额(格式为数字)', trigger: 'blur' },
                    ],
                    fileNum: [
                        { type:'number', min: 0, required: true, message: '请输入文件数上限(格式为数字)', trigger: 'blur' },
                    ],
                    spaceName: [
                        { required: true, validator: validateUrl, trigger: 'blur' },
                        { min: 4, max: 12, message: '长度在 4 到 12 个字符', trigger: 'blur' }
                    ]
                },
                unit: 2,
                resUnit: resUnit,
                pageSize: 10,
                allUserList: [],
                btnDisabled: false,
                path: this.$route.path.toLocaleUpperCase(),
                loading: false,
                remainFileTips:''
            }
        },
        watch:{
            diaData:{
                handler(val,oldval){
                    this.common = this.diaData;
                    this.resourceCon = JSON.parse(JSON.stringify(this.diaData.editData));
                    this.resourceCon.unit?this.unit = this.resourceCon.unit:'';
                    if(this.common.addResourceTab&&/HDFS/.test(this.path)){ 
                        this.getRemain();
                        this.getFileRemain();
                    }
                    if(this.common.resOperate&&(this.common.opeBtn==1||this.common.opeBtn==2)){ 
                        this.getUser();
                        this.getTenant();
                    }
                    if(this.common.editYARN&&/YARN/.test(this.path)){
                        this.btnDisabled = true;
                        managerApi.syncYARN({resourceId: this.resourceCon.resourceId,level:this.resourceCon.level}).then(res => {
                            // 同步资源后请求列表
                            this.btnDisabled = false;
                            managerApi.queueList({resourceId: this.resourceCon.resourceId}).then(res=>{
                                let result = res.pageList;
                                if(this.common.opeType==0){
                                    let obj = {
                                        queueName: '',
                                        ratio: 0,
                                        resourceId: ''
                                    };
                                    result.unshift(obj);
                                }
                                this.resourcePublic = result;
                                this.total = 0;
                                res.pageList.map(item => {
                                    this.total += (item.ratio-0);
                                })
                            })
                        }).catch(err => {
                            this.btnDisabled = false;
                        })
                    }
                },
                deep:true
            },
        },
        mounted(){
            this.addResourceTab = this.diaData.addResourceTab;
        },
        methods:{
            // 点击滑块旁按钮
            changCount(type,val,index){
                if(type==0&&val>0){ //减
                    this.resourcePublic[index].ratio--;
                }else if(type==1&&val<100){
                    this.resourcePublic[index].ratio++;
                }
                this.total = 0;
                this.resourcePublic.map(item => {
                    this.total += (item.ratio-0);
                })
            },
            yarnEdit(){
                let obj = {
                    level: this.resourceCon.level,
                    parentId: this.resourceCon.resourceId,
                    yarnInfoList: []
                }
                let total = 0;
                this.resourcePublic.map(item => {
                    let yarnInfo = {
                        resourceId: item.resourceId,
                        ratio: item.ratio,
                        queueName: item.queueName
                    };
                    total += item.ratio;
                    obj.yarnInfoList.push(yarnInfo);
                })
                if(this.common.opeType==0){ // 新建
                    let arr =  obj.yarnInfoList;
                    let queueName = arr[0].queueName;
                    if(!/(?!^(\d+)$)(?!^(_+)$)^[A-Za-z0-9_]{4,12}$/.test(queueName)){
                        Message.error("只能输入长度4-12位的数字、字母和'_'，并且不全为数字或'_'！")
                        return
                    }
                    for(let i=1;i<this.resourcePublic.length-1;i++){
                        if(this.resourcePublic[0].queueName == this.resourcePublic[i].queueName){
                            Message.error('已存在同名的队列名,请重新输入！')
                            return;
                        }
                    }
                    this.btnDisabled = true;
                    managerApi.postResYARN(obj).then( res => {
                        this.btnDisabled = false;
                        Message.success(res.msg);
                        this.common.editYARN = false;
                        this.$parent.getResourceList();
                    }).catch( err => {
                        this.btnDisabled = false;
                    })
                } else {
                    if(total != 100){
                        Message.error("队列占比之和需要等于100！");
                        return;
                    }
                    this.btnDisabled = true;
                    managerApi.modifyYARN(obj).then( res => {
                        this.btnDisabled = false;
                        this.common.editYARN = false;
                        Message.success('编辑成功！');
                        this.$parent.getResourceList();
                    }).catch( err => {
                        this.btnDisabled = false;
                    })
                } 
            },
            // 提交操作按钮
            submitTenant(){
                let that = this;
                if(this.common.opeBtn == '1'){//分配
                    let obj = {
                        resourceId: this.common.editData.resourceId,
                        userList: this.resourceCon.userList,
                        type: this.common.resType
                    }
                    if(false){
                        obj.powerList = this.resourceCon.powerList.join(',')
                    }
                    
                    // 用户是否选择

                    if(obj.userList.length == 0 && localStorage.selectLength == 0){
                        Message.error('请选择要分配的用户');
                        return;
                    }
                    this.btnDisabled = true;
                    if(/HDFS/.test(this.path)){
                        managerApi.distributeHDFS(obj).then( res =>{
                            that.successCB(2,'分配')
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                    if(/HBASE/.test(this.path)){
                        managerApi.distributeHBASE(obj).then( res =>{
                            that.successCB(2,'分配')
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                    if(/HIVE/.test(this.path)){
                        managerApi.distributeHIVE(obj).then( res =>{
                            that.successCB(2,'分配')
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                    if(/YARN/.test(this.path)){
                        delete obj.type;
                        managerApi.distributeYARN(obj).then( res =>{
                            that.successCB(2,'分配')
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                }
                if(this.common.opeBtn == '2'){//分享
                    let obj = {
                        resourceId: this.common.editData.resourceId,
                        // powerList: this.resourceCon.powerList.join(','),
                        tenantList: this.resourceCon.tenantList,
                        type: this.common.resType
                    }
                    that.btnDisabled = true;
                    if(/HDFS/.test(this.path)){
                        managerApi.shareResHdfs(obj).then( res =>{
                            that.successCB(2,'分享')
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                    if(/HBASE/.test(this.path)){
                        managerApi.shareResHBASE(obj).then( res =>{
                            that.successCB(2,'分享')
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                    if(/HIVE/.test(this.path)){
                        managerApi.shareResHIVE(obj).then( res =>{
                            that.successCB(2,'分享')
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                }
                if(this.common.opeBtn == '3'){//删除
                    let obj = {
                        keepData: this.idDelete?1:0,
                        resourceId: this.common.editData.resourceId,
                        url: this.common.editData.url
                    }
                    that.btnDisabled = true;
                    if(/HDFS/.test(this.path)){
                        managerApi.delResHDFS(obj).then( res =>{
                            that.successCB(2,'删除',1)
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                    if(/HBASE/.test(this.path)){
                        managerApi.delHBASERes(obj).then( res =>{
                            that.successCB(2,'删除',1)
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                    if(/YARN/.test(this.path)){
                        managerApi.delYARNRes({resourceId:this.common.editData.resourceId}).then( res =>{
                            that.successCB(2,'删除',1)
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                    if(/HIVE/.test(this.path)){
                        managerApi.delHIVERes(obj).then( res =>{
                            that.successCB(2,'删除',1)
                        }).catch( err =>{
                            that.btnDisabled = false;
                        })
                    }
                }
            },
            // 提交资源信息
            submitResourceCon(formName) {
                let that = this;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if(this.common.type == 'HDFS'){ //hdfs
                            let obj = {
                                capacity: that.resourceCon.capacity,
                                unit: that.unit,
                                fileNum: that.resourceCon.fileNum,
                                resourceId: that.common.editData.resourceId,
                                url: that.common.editData.allUrl + that.resourceCon.url,
                                userList: that.resourceCon.userList,
                                type: that.common.resType,
                                parentId: that.common.editData.resourceId  //父级ID
                            }
                            that.btnDisabled = true
                            managerApi.postResHdfs(obj).then(res => {
                                that.successCB(1,'资源创建');
                            }).catch(err => {
                                that.btnDisabled = false
                            })
                        }
                        if(this.common.type == 'HBASE'){
                            let obj = {
                                tenantList: that.resourceCon.tenantList,
                                userList: that.resourceCon.userList,
                                cate: that.resourceCon.clickStep,
                                type: that.common.resType,
                                parentId: that.common.editData.resourceId  //父级ID
                            }
                            switch(that.resourceCon.clickStep){
                                case 2: obj.tableName = that.resourceCon.spaceName;break; //表名
                                case 3: obj.columnFamilyName = that.resourceCon.spaceName;break; //列族
                            }
                            that.btnDisabled = true
                            managerApi.postResHBASE(obj).then(res => {
                                that.successCB(1,'资源创建');
                            }).catch(err => {
                                that.btnDisabled = false
                            })
                        }
                    }
                })
            },
        }
    }
</script>

<style lang="scss" scoped>
.resourceForm{
    .el-dialog{
        width: 600px;
    }
    .el-input,.el-select{
        width: 480px;
    }
    .capUnit{
        .el-input{
            width: 360px;
        }
        .el-select{
            width: 115px;
        }
    }
    
}
</style>
<style>
    .resourceForm.YARNForm .el-input{
        width: 200px;
    }
</style>